package util;

import ids.Sensor;

import java.util.HashSet;
import java.util.Vector;

import opt.FitnessFunction;

public class ContributingSensors {

	public Vector<Sensor> allSensors;

	public Vector<Sensor> contributingSensors;

	public boolean[] contributing;

	public ContributingSensors(Vector<Sensor> sensors) {
		this.allSensors = sensors;
		this.contributingSensors = new Vector<Sensor>();
		this.contributing = new boolean[sensors.size()];
		for (int i = 0; i < sensors.size(); i++) {
			this.contributing[i] = true;
		}
		this.markDuplicateSensors();
		this.markRedundantSensors();
		for (int i = 0; i < this.contributing.length; i++) {
			if (this.contributing[i])
				this.contributingSensors.add(this.allSensors.elementAt(i));
		}
	}

	public int getNumberOfContributingSensors() {
		return this.contributingSensors.size();
	}

	private void markDuplicateSensors() {
		HashSet<Integer> hs = new HashSet<Integer>();
		for (int index = 0; index < this.allSensors.size(); index++) {
			if (!hs.add(allSensors.elementAt(index).location.id))
				this.contributing[index] = false;
		}
	}

	private void markRedundantSensors() {
		FitnessFunction fitnessfunction = new FitnessFunction();
		fitnessfunction.evaluate(this.allSensors);
		int nVisiableAttacks = fitnessfunction.visiableAttacks;
		Sensor sensor;
		Vector<Sensor> backups = new Vector<Sensor>();
		for (int i = 0; i < this.allSensors.size(); i++) {
			backups.addElement(this.allSensors.elementAt(i));
		}
		int pointer = backups.size() - 1;
		int index = this.allSensors.size() - 1;
		while (pointer >= 0) {
			sensor = backups.elementAt(pointer);
			backups.remove(pointer);
			fitnessfunction.evaluate(backups);
			int newVisiableAttacks = fitnessfunction.visiableAttacks;
			if (newVisiableAttacks == nVisiableAttacks) {
				this.contributing[index] = false;
			} else {
				backups.add(pointer, sensor);
			}
			pointer--;
			index--;
		}
		//
		// for (int index = 0; index < this.allSensors.size(); index++) {
		// if (this.contributing[index]) {
		// sensor = this.allSensors.elementAt(index);
		// this.allSensors.remove(index);
		// fitnessfunction.evaluate(this.allSensors);
		// int newVisiableAttacks = fitnessfunction.visiableAttacks;
		// if (newVisiableAttacks == nVisiableAttacks) {
		// this.contributing[index] = false;
		// }
		// this.allSensors.add(index, sensor);
		// }
		// }
	}

}
